﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Enm;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxSpecialTaskController : Controller
    {
        YqdContext ctx;
        DdService ddService;

        public WxSpecialTaskController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        [User]
        public ActionResult GetList()
        {
            var tasktype = Form.GetInt("TaskType");
            var key = Form.GetString("key");
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", int.MaxValue);
            if (pagesize == 0) pagesize = int.MaxValue;
            var sql = "1=1 and isdel=0 ";
            if (tasktype > 0)
            {
                sql += " and [TaskType]={0}";
            }
            if (key.Trim() != "")
            {
                sql += " and lower(ltrim(rtrim([Name]))) like {1}";
            }
            var (totalcount, data) = ctx.Database.SqlPager<Yqd_SpecialTask>((page - 1) * pagesize, pagesize, "*", sql, "[Status] asc,[Instime] desc,[TaskID] asc", tasktype, "%" + key.ToLower().Trim() + "%");
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            var tps = ctx.Database.SqlQuery<Adp.Models.Tcm_Config>("select * from Tcm_Config where PlusID='Yqd' and Groupname='督查端' and Name!='' and ConfigTypeName='任务标签'");
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = data.Select(it => new
                {
                    it.TaskID,
                    it.Name,
                    LeadUnit = dept.FirstOrDefault(d => d.UnitCode == it.LeadUnit)?.Name,
                    Admins = string.Join(",", user.Where(m => ("," + it.Admins + ",").Contains("," + m.EmployeeCode + ",")).Select(n => n.Name)),
                    Inspector = string.Join(",", user.Where(m => ("," + it.Inspector + ",").Contains("," + m.EmployeeCode + ",")).Select(n => n.Name)),
                    Tags = string.Join(",", tps.Where(m => ("," + it.TaskTag + ",").Contains("," + m.ConfigID + ",")).Select(n => n.Name)),
                    Status = it.Status.ToString(),
                    it.Remark
                })
            });
        }

        [User]
        public ActionResult GetTaskList()
        {
            var TaskType = Form.GetInt("TaskType", 0);
            var year = Form.GetInt("Year");

            var l = WxUser.LogonInfo;
            var sql = "select * from Yqd_SpecialTask where IsDel=0 and Status=" + (int)栏目状态.正常;
            if (l.Dev == (int)设备平台.手机端)
            {
                sql += " and TaskType=" + (int)专项类型.专项督查;
            }
            if (year > 0)
            {
                sql += " and year(Instime)=" + year;
            }
            if (TaskType > 0)
            {
                sql += " and TaskType=" + TaskType;
            }
            if (l.Role.Any(it => it == 角色类型.督查管理员 || it == 角色类型.督查员))
            {
                sql += " and ((','+Admins + ',') like'%," + l.EmployeeCode + ",%' or (','+ Inspector + ',') like'%," + l.EmployeeCode + ",%' or (','+CoAdmins + ',') like'%," + l.EmployeeCode + ",%')";
            }
            var tasks = ctx.Database.SqlQuery<Yqd_SpecialTask>(sql);
            var tps = ctx.Database.SqlQuery<Adp.Models.Tcm_Config>("select * from Tcm_Config where PlusID='Yqd' and Groupname='督查端' and Name!='' and ConfigTypeName='" + (TaskType == (int)专项类型.专项交办 ? "专项" : "督查") + "类型' " + ((year > 0) ? " and value4 like '%" + year + "%'" : "") + " order by ConfigID");
            var temp = ctx.Yqd_SpecialTemplate.Where(it => it.IsDq).Select(it => new { it.TaskID, it.TemplateID }).ToList();
            var data = new List<dynamic>();
            var cIDs = new List<long>();
            data.Add(new
            {
                ID = 0,
                TaskID = 0,
                TemplateID = 0,
                Name = "全部"
            });
            foreach (var t in tasks.OrderBy(it => it.ConfigID == 0 ? long.MaxValue : it.ConfigID).ThenBy(it => it.Tactic))
            {
                if (t.ConfigID > 0)
                {
                    var c = tps.FirstOrDefault(m => m.ConfigID == t.ConfigID);
                    var Name = "";
                    //new 新增
                    if(c == null)
                    {
                        continue;
                    }
                    if (c != null) Name = c.Name;
                    if (cIDs.Contains(t.ConfigID)) continue;
                    data.Add(new
                    {
                        ID = t.TaskID,
                        TaskID = t.ConfigID.ToString(),
                        TemplateID = 0,
                        Name,
                        children = tasks.Where(it => it.ConfigID == t.ConfigID).Select(it => new
                        {
                            it.TaskID,
                            TemplateID = temp.FirstOrDefault(m => m.TaskID == it.TaskID)?.TemplateID ?? 0,
                            it.Name
                        })
                    });
                    cIDs.Add(t.ConfigID);
                }
                else
                {
                    data.Add(new
                    {
                        ID = t.TaskID,
                        t.TaskID,
                        TemplateID = temp.FirstOrDefault(m => m.TaskID == t.TaskID)?.TemplateID ?? 0,
                        t.Name
                    });
                }
            }
            return this.ToJson(new
            {
                success = true,
                data
            });
        }

        [User]
        public ActionResult GetsTypeList()
        {
            var TaskType = Form.GetInt("TaskType", (int)专项类型.专项督查);
            var tps = ctx.Database.SqlQuery<Adp.Models.Tcm_Config>("select * from Tcm_Config where PlusID='Yqd' and Groupname='督查端' and ConfigTypeName='" + (TaskType == (int)专项类型.专项交办 ? "专项" : "督查") + "类型'");
            return this.ToJson(new
            {
                success = true,
                data = tps.Select(it => new
                {
                    ConfigID = it.ConfigID.ToString(),
                    it.Name
                })
            });
        }

        [User]
        public ActionResult GetTagList()
        {
            var tps = ctx.Database.SqlQuery<Adp.Models.Tcm_Config>("select * from Tcm_Config where PlusID='Yqd' and Groupname='督查端' and ConfigTypeName='任务标签'");
            return this.ToJson(new
            {
                success = true,
                data = tps.Select(it => new
                {
                    ConfigID = it.ConfigID.ToString(),
                    it.Name
                })
            });
        }

        /// <summary>
        /// 添加督查栏目
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_SpecialTask model)
        {
            if (model.TaskType == 0)
            {
                model.TaskType = 专项类型.专项交办;
            }
            model.Status = 栏目状态.正常;
            model.Tactic = ctx.Database.MaxID("Yqd_SpecialTask", "Tactic");
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_SpecialTask.Add(model);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                if (model.Admins.HasValue())
                {
                    var codes = model.Admins.Split(",");
                    WxUser.AddUser(codes, (int)角色类型.督查管理员, (int)权限清单.允许操作);
                }
                if (model.CoAdmins.HasValue())
                {
                    var codes = model.CoAdmins.Split(",");
                    WxUser.AddUser(codes, (int)角色类型.督查管理员);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        /// <summary>
        /// 获取督查栏目
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Get()
        {
            var TaskID = Form.GetInt("TaskID");
            var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == TaskID);
            string UnitName = "", AdminName = "", InspectorName = "";
            var dept = ctx.Yqd_Unit.FirstOrDefault(d => d.UnitCode == task.LeadUnit);
            if (dept != null) UnitName = dept.Name;
            var names = ctx.Yqd_User.Where(m => ("," + task.Admins + ",").Contains("," + m.EmployeeCode + ",")).Select(n => n.Name).ToArray();
            if (names.Count() > 0) AdminName = string.Join(",", names);
            names = ctx.Yqd_User.Where(it => ("," + task.Inspector + ",").Contains("," + it.EmployeeCode + ",")).Select(n => n.Name).ToArray();
            if (names.Count() > 0) InspectorName = string.Join(",", names);
            var CoUnit = new JArray();
            if (task.CoUnit.HasValue()) CoUnit = JArray.Parse(task.CoUnit);
            return this.ToJson(new
            {
                success = true,
                task.TaskID,
                task.Name,
                ConfigID = task.ConfigID.ToString(),
                task.TaskType,
                task.TaskTag,
                task.LeadUnit,
                task.Admins,
                UnitName,
                InspectorName,
                task.Inspector,
                CoUnit,
                AdminName,
                task.Remark,
                task.TaskCode
            });
        }


        /// <summary>
        /// 修改督查栏目
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Edit(Yqd_SpecialTask model)
        {
            var c = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == model.TaskID);
            if (c != null)
            {
                c.Name = model.Name;
                c.TaskType = model.TaskType;
                c.ConfigID = model.ConfigID;
                c.TaskTag = model.TaskTag;
                c.Remark = model.Remark;
                c.LeadUnit = model.LeadUnit;
                c.CoUnit = model.CoUnit;
                c.CoAdmins = model.CoAdmins;
                c.Admins = model.Admins;
                c.TaskCode = model.TaskCode;
            }
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                if (model.Admins.HasValue())
                {
                    var codes = model.Admins.Split(",");
                    WxUser.AddUser(codes, (int)角色类型.督查管理员, (int)权限清单.允许操作);
                }
                if (model.CoAdmins.HasValue())
                {
                    var codes = model.CoAdmins.Split(",");
                    WxUser.AddUser(codes, (int)角色类型.督查管理员);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult GetTypeList()
        {
            var tps = new List<object>();
            var types = typeof(专项类型);
            foreach (int item in Enum.GetValues(types))
            {
                tps.Add(new { text = Enum.GetName(types, item), value = item.ToString() });
            }
            return this.ToJson(new
            {
                success = true,
                types = tps
            });
        }

        [User]
        public ActionResult UpdateInspector()
        {
            var TaskID = Form.GetInt("TaskID");
            var Inspector = Form.GetString("Inspector");
            var ret = ctx.Database.ExecuteSql("update Yqd_SpecialTask set Inspector={1} where TaskID={0};", TaskID, Inspector);
            if (ret > 0)
            {
                if (Inspector.HasValue())
                {
                    var codes = Inspector.Split(",");
                    WxUser.AddUser(codes, (int)角色类型.督查员);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult UpdateStatus()
        {
            var TaskID = Form.GetLong("TaskID");
            var state = Form.GetInt("state");
            var ret = ctx.Database.ExecuteSql("update Yqd_SpecialTask set Status={1} where TaskID={0};", TaskID, state);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var l = WxUser.LogonInfo;
            if (!l.Role.Contains(角色类型.管理员))
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "无权限删除"
                });
            }
            var TaskID = Form.GetLong("TaskID");
            //var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == TaskID);
            var ret = ctx.Database.ExecuteSql("update Yqd_SpecialTask set IsDel=1 where TaskID={0};", TaskID);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
